﻿///<reference path="jquery.js" />
///<reference path="MaxLib.js" />

var gLastActiveGroupID='group_0';
var gGroupList=[];
var gPluginPath=external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME);
$(function(){

    CreateGroup();
	$("#groupList").sortable({
		stop:function()
		{
			SaveGroup();
		}
	});
});

function SaveGroup()
{
	var gp=[];
	$("#groupList li").each(function(i){
		var gName=trim(this.innerText);
		if(gName)
		{
			if(gName.toLowerCase()!="temp")
			{		
				gp.push(trim(this.innerText));
			}
		}				
	});
	external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\groups.txt",gp.join("\r\n"));
	try
	{
	fso.CreateFolder(gPluginPath+"userData\\image\\TEMP");
	}
	catch(e){}
	var dFn="userData\\image\\TEMP\\description.txt";
	if(!fso.FileExists(gPluginPath+dFn))
	{
		external.writeFile(SECURITY_ID,PLUGIN_NAME,dFn,"作者：pharaoh.cnblogs.com\r\n描述：此处存放临时收集的表情。\r\n时间：2008-2-11");
	}
}

function CreateGroup()
{    
    var groupText=external.readFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\groups.txt");
    gGroupList=[];
    gLastActiveGroupID="group_0";
    if(groupText)
    {
    	groupText=clear0(groupText);
        gGroupList=groupText.split("\r\n");
    }
    gGroupList=["TEMP"].concat(gGroupList);
    var html=[];
    //html.push("<li id='group_0' unselectable='on'>TEMP</li>");
    for(var i=0;i<gGroupList.length;i++)
    {
        html.push("<li onclick='GroupClick(this);' id='group_",i,"'>",gGroupList[i],"</li>");
    }
    $('#groupList').html(html.join(""));
    
    $('#group_0').addClass('current');
    LoadGroupDescription(0);
    /*
    $('#groupList li').click(function(o){
        //printobj(this);
        if(this.className=='current') {return;}
        $('#'+gLastActiveGroupID).removeClass('current');
        gLastActiveGroupID=this.id;
        $('#'+gLastActiveGroupID).addClass('current');
        LoadGroupDescription(gLastActiveGroupID.split("_")[1]);
        
    });
    */
    $("#groupList").sortableRefresh({});
}

function GroupClick(o)
{
        if(o.className=='current') {return;}
        $('#'+gLastActiveGroupID).removeClass('current');
        gLastActiveGroupID=o.id;
        $('#'+gLastActiveGroupID).addClass('current');
        LoadGroupDescription(gLastActiveGroupID.split("_")[1]);	
}


var gImgList=[];

function LoadGroupDescription(groupID)
{
    var groupName=gGroupList[groupID];
    //alert('Load:'+groupName);    
    var descriptionText=external.readFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\"+groupName+"\\description.txt");
    //alert(descriptionText);//
    if(descriptionText)
    {
    	descriptionText=clear0(descriptionText);
    	document.getElementById("groupDescription").value=descriptionText;
    }
    else
    {
    	document.getElementById("groupDescription").value="";
    }
	var listText=external.readFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\"+groupName+"\\list.txt");
	var listUrl=[];
	if(listText)
	{
		listText=clear0(listText);
		listUrl=listText.split("\r\n");
	}
	var count=listUrl.length;
	var msg="当前组表情个数："+count;
	if(count==0)
	{
		msg="<font color='blue'>"+msg+"</font>";
		document.getElementById("btnDeleteGroup").disabled = false;
	}	
	else
	{
		document.getElementById("btnDeleteGroup").disabled = true;
	}
	if(groupName.toLowerCase()=="temp")
	{
		document.getElementById("btnDeleteGroup").disabled = true;
	}
	document.getElementById("messageBox").innerHTML=msg;
	
}

function groupDescriptionChanged()
{
    var groupName=gGroupList[gLastActiveGroupID.split("_")[1]];
    var descriptionText=document.getElementById("groupDescription").value;
    external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\"+groupName+"\\description.txt",descriptionText);
    
}


function AddGroup()
{
    var newGroupName = window.prompt("请输入新增加的组名称(首尾的空格会被去掉)：","新表情组");

    if(newGroupName)
    {        
        newGroupName=trim(newGroupName);      
        if(!newGroupName) return;
        if(newGroupName.length>10)
        {
        	alert("组名称不得长于10！");
        	return;
        }
        var lGroupName=newGroupName.toLowerCase();
        var index= indexOfinArray(gGroupList,lGroupName);
        if(index>=0)
        {
            alert("已经存在同名的组，没有增加新的组！");
            return;        
        }
        try
        {
        	fso.CreateFolder(gPluginPath+"userData\\image\\"+newGroupName);
        }
        catch(e)
        {
        	if(e.number!=-2146828230)
        	{
	        	alert("新增组没有成功!\n"+e.number+":" + e.message);
	        	return;
        	}
        }
        gGroupList.push(newGroupName);
        $("#groupList").append("<li onclick='GroupClick(this);' id='group_"+(gGroupList.length-1)+"'>"+newGroupName+"</li>");
        $("#groupList").sortableRefresh({});
        SaveGroup();
    }
}

function EditGroup()
{
    var groupID=gLastActiveGroupID.split('_')[1];
    /*
    if(groupID==0)
    {
        alert('不能更改TEMP的名称!\n请新建一个组，将表情移动到对应的组中。');
        return;
    }
    */
    var groupName=gGroupList[gLastActiveGroupID.split('_')[1]];

    var newGroupName = window.prompt("请输入新的组名称(首尾的空格会被去掉)：",groupName);

    if(newGroupName)
    {
        
        newGroupName=trim(newGroupName);      
        if(!newGroupName) return;
        if(newGroupName.length>10)
        {
        	alert("组名称不得长于10！");
        	return;
        }        
        var lGroupName=newGroupName.toLowerCase();
        if(lGroupName==groupName.toLowerCase())
        {
            //alert('名称没有更改');
            return;
        }
        var index= indexOfinArray(gGroupList,lGroupName);
        if(index>=0)
        {
            alert("已经存在同名的组，更名没有成功！");
            return;        
        }
        
        var path= gPluginPath+"userData\\image\\";
        var returnText = DirRename(path+ groupName,path+newGroupName);
        if(returnText)
        {
            alert("更改组名称错误！\n"+returnText);
            return;
        }

        gGroupList[groupID]=newGroupName;
        $('#'+gLastActiveGroupID).text(newGroupName);
        
        SaveGroup();
        
        //var newGroupList=gGroupList.slice(1);
        //external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\groups.txt",newGroupList.join("\r\n"));
        
    }
}

function DeleteGroup()
{
    //alert('//todo:DeleteGroup');
    var groupID=gLastActiveGroupID.split('_')[1];
    var groupName=gGroupList[groupID];  
    if(groupName.toLowerCase()=="temp")
    {
    	alert("不能删除临时组(TEMP)!");
    	return;
    } 

    var imgListText=external.readFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\"+groupName+"\\list.txt");
    var imgList=[];
    if(imgListText)
    {
    	imgListText=clear0(imgListText);
    	imgList=imgListText.split("\r\n");
    }
    if(imgList.length>0)
    {
		alert("当前组下的表情不为空，请先将此组下表情移动到其他组！"); 
		return;
    }
    if(window.confirm('确实要删除分组“'+groupName+'”吗？'))
    {
    	//alert('dele:'+groupName);
    	try
    	{
    	fso.DeleteFolder(gPluginPath+"userData\\image\\"+groupName,true);
		}
		catch(e)
		{
			alert("删除组时出错：\n)"+ e.message);
		}
    	$("#"+gLastActiveGroupID).text("");
    	SaveGroup();
    	CreateGroup();
    }
    
     
}

function DownloadImg()
{
    var groupID=gLastActiveGroupID.split('_')[1];
    
    var groupName=gGroupList[groupID];
	

	
	var urls=[];
	var urls=gImgList;
	/*var tmpImgList = window.external.readFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\temp\\list.txt");
	if(tmpImgList)
	{
		urls=tmpImgList.split("\r\n");
	}
	*/
	var getImgList=[];
	var getImgCount=0;
	var mb=window.document.getElementById("messageBox");
	for(var i=0;i<urls.length;i++)
	{
		mb.innerText="正在获取图片缩略图：["+(i+1)+"/"+urls.length+"]:"+urls[i];
		var r= getImg(SECURITY_ID,PLUGIN_NAME,urls[i],groupName);
		if(r==0)
		{
			getImgCount++;
		}
		/*
		if((r==0)||(r==-1))
		{
			getImgList.push(encodeURIComponent(urls[i]));
		}
		*/
	}
	//window.external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\temp\\getOK.txt",getImgList.join("\r\n"));
	mb.innerText="获取完成！"+"["+getImgCount +"/"+urls.length+"] " ;
	//alert(gLastActiveGroupID);
	if(getImgCount>0)
	{
		LoadGroupDescription(groupID);
	}
}
function getImg(SECURITY_ID,PLUGIN_NAME,imgPath,groupName)
{


	var pharaoh_pluginPath=external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME);
	
	var dosFn= groupName + "\\" +encodeURIComponent(imgPath);
	if(fso.FileExists(pharaoh_pluginPath+"userData\\image\\"+dosFn+".png")) 
	{
		return -1;
	}
	var ws= external.max_activex(SECURITY_ID,'WScript.Shell'); 
	//alert(path);
	//ws.run('notepad.exe "'+external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME)+'autorunUrl.lst"')
//	var r= ws.run('cmd.exe /C "'+external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME)+'tool\\good\\getimg.bat" "http://www.imagemagick.com/images/fuzzy-magick.png"',5,true);
	var batFn="tool\\getimg.txt";

    var bat=window.external.readFile(SECURITY_ID,PLUGIN_NAME,batFn);
	bat=clear0(bat);

    bat= bat.replace(/IMAGE_PATH/g,imgPath);
    bat=bat.replace(/IMAGE_NAME/g, dosFn.replace(/%/g,"%%"));

    window.external.writeFile(SECURITY_ID,PLUGIN_NAME,"tool\\tmpBat.bat",bat);
	var r= ws.run('cmd /C cd /d '+external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME)+'tool\\ &tmpBat.bat',7,true);

	ws=null;
	return r;
}


function printobj(o)
{
	var msg='';
	for(var k in o)
	{
		msg+=k+"\t:"+o[k]+"\n";
	}
	alert(msg);
}


function indexOfinArray(list,str)
{
    var lstr=str.toLowerCase();
    for(var i=0;i<list.length;i++)
    {
        if(lstr==list[i].toLowerCase())
        {          
            return i;
        }
    }
    return -1;
}

var fso=external.max_activex(SECURITY_ID,"Scripting.FileSystemObject");
function DirRename(oldName,NewName)
{
    try
    {
    fso.MoveFolder(oldName,NewName);
    }
    catch(e)
    {
        return e.message;
    }
    return null;
}
